//上传MPC分片到云端弹窗
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:http/http.dart';
import 'package:lib_apple_auth_storage/lib_apple_auth_storage.dart';
import 'package:lib_cloud_storage/lib_cloudstorage.dart';
import 'package:lib_database/sp.dart';
import 'package:lib_util/lib_util.dart';

import '../../../../kai_print.dart';
import '../../../../module_common/bridge/native_channel_bridge.dart';
import '../../../../module_common/network/http_chain_list.dart';
import '../../../../module_common/provider/wallet_info_provider.dart';
import '../../../../module_common/utils/util.dart';
import '../../../../module_common/widgets/button/bottom_button.dart';
import '../../../../module_common/widgets/dialog/bottom_sheet_widget.dart';
import '../../pages/wallet_mpc_securitymanager.dart';
import '../RotationImageWidget.dart';

enum UploadStatus { success, faild, ing }

class WalletMPCUploadSheet extends StatefulWidget {
  final String pk;
  final MPCType type;
  final void Function(MPCStatus) callback;

  const WalletMPCUploadSheet({Key? key, required this.pk, required this.type, required this.callback})
      : super(key: key);

  @override
  _WalletMPCUploadSheetState createState() => _WalletMPCUploadSheetState();
}

class _WalletMPCUploadSheetState extends State<WalletMPCUploadSheet> {
  UploadStatus _status = UploadStatus.ing;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // context.read<TokenListNotifier>().resetSearchText();

      //进来后自动上传
      uploadKey();
    });
  }

  void uploadKey() {
    switch (widget.type) {
      case MPCType.googleDrive:
        _googleUpdata();
        break;
      case MPCType.iCloud:
        _iCloudUpdata();
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheetWidget(
        showCloseBtn: false,
        title: widget.type == MPCType.googleDrive ? 'Google Drive' : 'iCloud',
        expand: false,
        child: Container(
          padding: EdgeInsets.only(left: 20.w, right: 20.w),
          child: Column(
            children: [
              SizedBox(height: 15.w),
              Container(
                width: 94.w,
                height: 94.w,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(94).w), // 创建一个圆形边框
                    border: Border.all(width: 1, color: '#E0E0E0'.toColor())),
                child: Stack(
                  alignment: AlignmentDirectional.center,
                  children: [
                    Image.asset(
                        widget.type == MPCType.googleDrive
                            ? 'assets/images/wallet/upload_googledrive.png'
                            : 'assets/images/wallet/upload_icloud.png',
                        width: 70.w,
                        height: 70.w),
                    Align(alignment: Alignment.bottomRight, child: statusImage())
                  ],
                ),
              ),
              SizedBox(height: 13.w),
              Text(
                statusTip(),
                style: TextStyle(color: "#333333".toColor(), fontSize: 16.sp, fontWeight: FontWeight.w500),
              ),
              SizedBox(height: 20.w),
              statusButton(),
              SizedBox(
                height: (MediaQuery.of(context).padding.bottom + 10).w,
              )
            ],
          ),
        ));
  }

  void closeSheet() {
    MPCStatus temp = MPCStatus.again;
    if (_status == UploadStatus.success) {
      temp = MPCStatus.success;
    }
    if (_status == UploadStatus.faild) {
      temp = MPCStatus.again;
    }
    widget.callback(temp);
    Navigator.pop(context);
  }

//根据当前上传的状态返回图标提示
  Widget statusImage() {
    switch (_status) {
      case UploadStatus.success:
        return Image.asset('assets/images/wallet/ok.png', width: 26.w, height: 26.w);
      case UploadStatus.faild:
        return Image.asset('assets/images/wallet/no.png', width: 26.w, height: 26.w);
      case UploadStatus.ing:
        return RotationImage(image: Image.asset('assets/images/wallet/uploading.png', width: 26.w, height: 26.w));
    }
  }

  //根据当前上传的状态返回文字提示
  String statusTip() {
    switch (_status) {
      case UploadStatus.success:
        return 'Upload Completed';
      case UploadStatus.faild:
        return 'Upload Failed';
      case UploadStatus.ing:
        return 'Uploading…';
    }
  }

  //根据当前上传的状态返回底部按钮
  Widget statusButton() {
    switch (_status) {
      case UploadStatus.success:
        return PublicButton(
          text: "Return",
          margin: EdgeInsets.zero,
          onClick: closeSheet,
        );
      case UploadStatus.faild:
        return BottomBtn(
            height: 46.w,
            textList: ["Return", 'Reupload'],
            onCancel: () {
              closeSheet();
            },
            onConfirm: () {
              //上传key
              uploadKey();
            });

      case UploadStatus.ing:
        return Container();
    }
  }

  Widget checkBox({required String text, required bool isCheck, required void Function(bool) onChanged}) {
    return Container(
      padding: EdgeInsets.only(left: 15.w, top: 15.w, bottom: 15.w),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: '#F6F6F6'.toColor()),
      child: Row(
        children: [
          Expanded(child: Text(text, style: TextStyle(color: "#868391".toColor(), fontSize: 12.sp))),
          InkWell(
            child: Container(
              padding: EdgeInsets.only(left: 5.w, top: 10.w, bottom: 10.w, right: 16.w),
              child: Image.asset(
                  isCheck ? 'assets/images/wallet/delete_check.png' : 'assets/images/wallet/delete_uncheck.png',
                  width: 16.w,
                  height: 16.w),
            ),
            onTap: () {
              isCheck = !isCheck;
              //改变颜色

              onChanged(isCheck);
            },
          )
        ],
      ),
    );
  }

  ///gogle deive
  void _googleUpdata() async {
    try {
      //获取到上传的文件ID
      String uid = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      String email = NativeChannelBridge.instance.appCommMsg?.google_email ?? '';
      String salt = SP().getRandomSalt() ?? "";
      try{
        // 判断 盐 服务端盐 是否真是存在
        String? serverKey = (await WalletCheck.getServerKey()).$1;
        print('serverKey.isNotEmpty ${serverKey.isNotEmpty}');
        if(serverKey.isNotEmpty){
          salt = await HttpChainList().getSaltByUrl()??'';
          print('_googleUpdata salt $salt');
        }
      }catch(e){
        print(' $e');
      }
      setState(() {
        _status = UploadStatus.ing;
      });
      // print("req授权开始");
      // GoogleLoginResult req = await LibCloudStorage.startGoogleLogin();
      // print("req = ${req.idToken}");
      String fileID = await LibCloudStorage.uploadToGoogleCloud(email, widget.pk, uid, salt);
      print('fileID ${fileID}');
      if (fileID.isEmpty) {
        setState(() {
          _status = UploadStatus.faild;
        });
      } else {
        //保存到数据库
        context.read<WalletInfoNotifier>().updateWalletGoogleFileId(fileID);

        setState(() {
          _status = UploadStatus.success;
        });
      }
    } catch (e) {
      Log().d(e);
      //上传失败
      setState(() {
        _status = UploadStatus.faild;
      });
    }
  }

  //iCloud上传
  void _iCloudUpdata() async {
    String uid = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    String salt = SP().getRandomSalt() ?? "";
    try{
      // 判断 盐 服务端盐 是否真是存在
      String? serverKey = (await WalletCheck.getServerKey()).$1;
      print('serverKey.isNotEmpty ${serverKey.isNotEmpty}');
      if(serverKey.isNotEmpty){
        salt = await HttpChainList().getSaltByUrl()??'';
        print('_iCloudUpdata salt $salt');
      }
    }catch(e){
      kaiPrint('error $e');
    }
    setState(() {
      _status = UploadStatus.ing;
    });

    var result = await LibAppleAuthStorage.storage(uid, widget.pk, salt);

    context.read<WalletInfoNotifier>().updateWalletAppleFileId('${uid}_${salt}');
    if (result) {
      setState(() {
        _status = UploadStatus.success;
      });
    } else {
      setState(() {
        _status = UploadStatus.faild;
      });
    }
  }
}
